﻿using System.Text.Json;
using IPTools.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using UAParser;
using Vin.Tool.Core.JsonCategory;
using Vin.Tool.Core.StreamCategory;
using Vin.Tool.Domain.SystemModel;

namespace Vin.Tool.Core.NetCategory;

public static partial class Extension
{
    /// <summary>
    /// 获取客户端IP
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static string GetClientUserIp(this HttpContext context)
    {
        var result = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
        if (string.IsNullOrEmpty(result))
        {
            result = context.Connection.RemoteIpAddress?.ToString();
        }

        if (string.IsNullOrEmpty(result))
            throw new Exception("获取IP失败");

        if (result.Contains("::1"))
            result = "127.0.0.1";

        result = result.Split(",").FirstOrDefault() ?? result;
        result = result.Replace("::ffff:", "");
        result = result.Split(':')?.FirstOrDefault() ?? "127.0.0.1";
        result = HttpContextTool.IsIp(result) ? result : "127.0.0.1";
        return result;
    }

    /// <summary>
    /// 获取浏览器信息
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static ClientInfo GetClientInfo(this HttpContext context)
    {
        return HttpContextTool.ParserUserAgent(context.Request.Headers["User-Agent"]!);
    }

    /// <summary>
    /// 获取客户端信息
    /// </summary>
    public static HttpContextClientDetailModel GetClientDetail(this HttpContext context, bool parseClient = false)
    {
        var ip = context.GetClientUserIp();

        IpInfo? ipInfo;
        try
        {
            ipInfo = IpTool.Search(ip);
        }
        catch
        {
            ipInfo = IpTool.Search(ip);
        }

        if (ipInfo == null) throw new Exception("系统繁忙，请稍后再试");

        var model = new HttpContextClientDetailModel()
        {
            Ip = ip,
            IpInfo = ipInfo,
            Location = $"{ipInfo.Country} {ipInfo.Province} {ipInfo.City} {ipInfo.NetworkOperator}",
        };

        if (parseClient)
        {
            var clientInfo = context.GetClientInfo();
            model.ClientInfo = clientInfo;
            model.Browser = clientInfo.UA.ToString();
            model.Os = clientInfo.OS.ToString();
            model.UserAgent = clientInfo.String;
            model.Device = clientInfo.Device.ToString();
        }

        return model;

        // var clientInfo = context.GetClientInfo();
        // return new HttpContextClientDetailModel()
        // {
        //     Ip = ip,
        //     IpInfo = ipInfo,
        //     Location = $"{ipInfo.Country} {ipInfo.Province} {ipInfo.City} {ipInfo.NetworkOperator}",
        //     ClientInfo = clientInfo,
        //     Device = clientInfo.Device.ToString(),
        //     Browser = clientInfo.UA.ToString(),
        //     Os = clientInfo.OS.ToString(),
        //     UserAgent = clientInfo.String,
        // };
    }

    #region 读取Body

    private static string BodyKey = "Body";

    /// <summary>
    /// 读取请求Body
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static Task<string> ReadToString(this HttpContext context)
    {
        var body = context.GetBody<string>();
        if (body != null) return Task.FromResult(body);
        return context.Request.Body.ReadToString();
    }

    public static Task<JsonElement?> ReadToJson(this HttpContext context)
    {
        var body = context.GetBody<JsonElement?>();
        if (body != null) return Task.FromResult(body);
        return context.Request.Body.ReadToJson();
    }

    public static Task<T?> ReadToJson<T>(this HttpContext context)
    {
        var body = context.GetBody<T?>();
        if (body != null) return Task.FromResult(body)!;
        return context.Request.Body.ReadToJson<T>();
    }

    public static T? GetBody<T>(this HttpContext context)
    {
        return context.GetItems<T?>(BodyKey);
    }

    #endregion

    /// <summary>
    /// 转换为Curl
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public static string ToCurl(this HttpContext context)
    {
        return HttpContextTool.ToCurl(context);
    }

    public static string FormString(this HttpContext context)
    {
        return HttpContextTool.FormString(context.Request.Form);
    }

    public static Dictionary<string, string> FormDictionary(this HttpContext context)
    {
        return HttpContextTool.FormDictionary(context.Request.Form);
    }

    public static void SetItems<T>(this HttpContext context, string key, T value)
    {
        context.Items.Add(key, value);
    }

    public static T? GetItems<T>(this HttpContext context, string key)
    {
        return (T?)context.Items[key];
    }

    public static void GenerateRequestId(this HttpContext context)
    {
        context.SetItems("RequestId", Guid.NewGuid().ToString("N"));
    }

    public static string GetRequestId(this HttpContext context)
    {
        return context.GetItems<string>("RequestId") ?? string.Empty;
    }

    public static T QueryToObject<T>(this HttpContext context,
        JsonTool.JsonOptionsType type = JsonTool.JsonOptionsType.None) where T : new()
    {
        var queryJsonStr = context.Request.Query.ToDictionary(m => m.Key, m => m.Value.ToString()).ToJson();
        return (type switch
        {
            JsonTool.JsonOptionsType.CamelCase => queryJsonStr.ToCamelCaseObject<T>(),
            JsonTool.JsonOptionsType.MiddleLineLower => queryJsonStr.ToMiddleLineObject<T>(type),
            JsonTool.JsonOptionsType.MiddleLineUpper => queryJsonStr.ToMiddleLineObject<T>(type),
            JsonTool.JsonOptionsType.UnderLineLower => queryJsonStr.ToUnderLineObject<T>(type),
            JsonTool.JsonOptionsType.UnderLineUpper => queryJsonStr.ToUnderLineObject<T>(type),
            JsonTool.JsonOptionsType.None => queryJsonStr.ToObject<T>(),
            _ => new T()
        })!;
    }
    
    public static T FormToObject<T>(this HttpContext context,
        JsonTool.JsonOptionsType type = JsonTool.JsonOptionsType.None) where T : new()
    {
        var queryJsonStr = context.Request.Form.ToDictionary(m => m.Key, m => m.Value.ToString()).ToJson();
        return (type switch
        {
            JsonTool.JsonOptionsType.CamelCase => queryJsonStr.ToCamelCaseObject<T>(),
            JsonTool.JsonOptionsType.MiddleLineLower => queryJsonStr.ToMiddleLineObject<T>(type),
            JsonTool.JsonOptionsType.MiddleLineUpper => queryJsonStr.ToMiddleLineObject<T>(type),
            JsonTool.JsonOptionsType.UnderLineLower => queryJsonStr.ToUnderLineObject<T>(type),
            JsonTool.JsonOptionsType.UnderLineUpper => queryJsonStr.ToUnderLineObject<T>(type),
            JsonTool.JsonOptionsType.None => queryJsonStr.ToObject<T>(),
            _ => new T()
        })!;
    }
}